/**
 * @desc
 * @author  刘贺[of2220]
 * @company qianmi.com
 * @Date    2017/2/10
 */
"use strict";
const express = require('express');
let router = express.Router();
const _ = require('@qianmi/x-site-common/util/response-util');
const RelatedImgInfoService = require('@qianmi/x-site-database/service/relatedimginfo-service');
const envCode = require('@qianmi/x-site-common/util/common-util').getEnvCode();
const uuid = require('node-uuid');
let Busboy = require('busboy');
let ossConfig = require('../config').ossConfig;
let ossClient = require('@qianmi/x-site-common/util/oss').getOssClient(ossConfig);

const prefix = 'http://qianmi-web.oss-cn-hangzhou.aliyuncs.com';

router.post('/createNewCate', function (req, res, next) {
    (async() => {
        const {id, name, pid} = req.body;
        //TODO校验id 与 pid
        try {
            let result = await RelatedImgInfoService.createNewCate({id, name, pid});
            res.json(_.resultSucess(result));
        } catch (e) {
            console.log(e);
            res.json(_.resultfailure(e));
        }
    })()
});

router.post('/deleteCate', function (req, res, next) {
    (async() => {
        const {id} = req.body;
        try {
            let result = await RelatedImgInfoService.deleteCate({id});
            res.json(_.resultSucess(result));
        } catch (e) {
            console.log(e);
            res.json(_.resultfailure(e));
        }
    })()
});

router.post('/updateCateName', function (req, res, next) {
    (async() => {
        const {id, name} = req.body;
        try {
            let result = await RelatedImgInfoService.updateCateName({id, name});
            res.json(_.resultSucess(result));
        } catch (e) {
            console.log(e);
            res.json(_.resultfailure(e));
        }
    })()
});

router.post('/getCategoryTree', function (req, res, next) {
    (async() => {
        try {
            let result = await RelatedImgInfoService.getCategoryTree();
            res.json(_.resultSucess(result));
        } catch (e) {
            console.log(e);
            res.json(_.resultfailure(e));
        }
    })()
});

router.post('/getCateTreeAndImgByPid', function (req, res, next) {
    (async() => {
        let {id, pageNum, pageSize} = req.body;
        pageNum = parseInt(pageNum, 10);
        pageSize = parseInt(pageSize, 10);
        try {
            let result = await RelatedImgInfoService.getCateTreeAndImgByPid({id, pageNum, pageSize});
            res.json(_.resultSucess(result));
        } catch (e) {
            console.log(e);
            res.json(_.resultfailure(e));
        }
    })()
});

/******************************* 图片相关 ***********************************/
router.post('/imgUpload',function (req,res,next) {
    let fileSize = 1024 * 1024; //1M
    let buff = [];
    let extName = 'jpg';    //default
    let contentLength = req.headers['content-length'] || 0;
    console.log(contentLength);
    if (contentLength > fileSize) {
        res.status(413).end();
        return;
    }
    let busboy = new Busboy({
        headers: req.headers,
        limits: {fileSize}
    });
    busboy.on('file', function (fieldname, file, filename, encoding, mimetype) {
        extName = filename.split('.')[filename.split('.').length - 1];
        file.on('data', function (data) {
            buff.push(data);
        });
        file.on('end', function () {
            let remotePath = `x-site-admin/${envCode}/public/images/${uuid.v1()}.${extName}`;
            ossClient.putObjectAbsolute(Buffer.concat(buff), remotePath).then((result) => {
                res.send({"result": "ok", "url":result.name});
            })
        });
    });
    busboy.on('field', function (fieldname, val, fieldnameTruncated, valTruncated, encoding, mimetype) {

    });
    busboy.on('finish', function () {

    });
    req.pipe(busboy);
});

router.post('/saveImage', function (req, res, next) {
    (async() => {
        let {pid, name, src, des, keyword, fileSize, imgSize} = req.body;
        try {
            let result = await RelatedImgInfoService.saveImage({pid, name, src, des, keyword, fileSize, imgSize});
            res.json(_.resultSucess(result));
        } catch (e) {
            console.log(e);
            res.json(_.resultfailure(e));
        }
    })()
});

router.post('/deleteImage', function (req, res, next) {
    (async() => {
        let {id} = req.body;
        try {
            let result = await RelatedImgInfoService.deleteImage({id});
            res.json(_.resultSucess(result));
            await ossClient.delObject(result.src)
        } catch (e) {
            console.log(e);
            res.json(_.resultfailure(e));
        }
    })()
});

router.post('/updateImageInfo', function (req, res, next) {
    (async() => {
        let {id, imgInfo} = req.body;
        if (typeof imgInfo === 'string') {
            imgInfo = JSON.parse(imgInfo);
        }
        try {
            let result = await RelatedImgInfoService.updateImageInfo({id, imgInfo});
            res.json(_.resultSucess(result));
        } catch (e) {
            console.log(e);
            res.json(_.resultfailure(e));
        }
    })()
});

router.post('/getImageList', function (req, res, next) {
    (async() => {
        let {pid, pageNum, pageSize} = req.body;
        pageNum = parseInt(pageNum, 10);
        pageSize = parseInt(pageSize, 10);
        try {
            let result = await RelatedImgInfoService.getImageList({pid, pageNum, pageSize});
            res.json(_.resultSucess(result));
        } catch (e) {
            console.log(e);
            res.json(_.resultfailure(e));
        }
    })()
});


module.exports = router;
